package gdt.service;

import java.util.List;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import gdt.dao.ClientDAO;
import gdt.entity.Client;
import gdt.entity.Member;
import gdt.service.utils.Validator;


public class ClientService {
	
	@Transactional(readOnly=true)
	public Client findById(long id){
		return clientDao.findById(id);
	}
	
	@Transactional(readOnly=true)
	public List<Client> findByUser(String username){
		Member user = (Member) userDetailsService.loadUserByUsername(username);
		
		return user.getGroup().getClients();
	}
	

	public boolean save(Client client, MessageContext messageContext){
		if(validate(client,messageContext)){
			save(client);
			return true;
		}
		else{
			return false;
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public void save(Client client){
		client = clientDao.makePersistent(client);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public boolean delete(Client client, MessageContext messageContext){
		if(client.getProjects().isEmpty()){
			client.getGroup().removeClient(client);
			clientDao.makeTransient(client);
			return true;
		}else{
			messageContext.addMessage((new MessageBuilder()).error().code("error_client_delete").build());
			return false;
		}
	}
	
	@Transactional(readOnly=true)
	public Client setup(String username){
		Client c = new Client();
		Member user = (Member) userDetailsService.loadUserByUsername(username);
		c.setGroup(user.getGroup());
		
		return c;
	}
	
	
	/********************************* DAO's *********************************/
	
	private ClientDAO clientDao;
	
	public void setClientDao(ClientDAO clientDao) {
		this.clientDao = clientDao;
	}

	private UserDetailsService userDetailsService;

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	
	/******************************* Validation *******************************/
	
	private Validator validator;
	
	public boolean validate(Client client, MessageContext context){
		return validator.validate(client, context);
	}
	
	public Validator getValidator() {
		return validator;
	}

	public void setValidator(Validator validator) {
		this.validator = validator;
	}
}
